import 'package:Sayagh/Configs.dart';
import 'package:Sayagh/i18n/i18nLocale.dart';
import 'package:Sayagh/tablepress/csv.dart';
import 'package:flutter/material.dart';

class ShowTable extends StatefulWidget {
  final String titleFa;
  final String website;
  final String tableName;
  final int hasSubTable;
  final int hasCategoryColumn;
  final int hasCategorySubColumn;

  ShowTable(this.titleFa, this.tableName,
      {this.website = "http://sayagh.asnafhormozgan.ir/",
      this.hasSubTable = 0,
      this.hasCategoryColumn = 0,
      this.hasCategorySubColumn = 0});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ShowTable();
  }
}

class _ShowTable extends State<ShowTable> {
  bool firstTimeDropDownMenu = true;
  String selectedValueDropDownMenu;
  List<List> data;
  List<String> head;
  Map<String, List<Map>> _categoryColumnGroup;
  TextEditingController editingController = TextEditingController();

  Map<String, List<Map>> categoryColumnGroup(List csvList) {
    if (csvList.length < 2) return null;
    List<String> head = csvList[0];
    List<List> data = csvList[1];
    Map<String, List<Map>> mappedData = new Map();
    if (data.length < 1) return null;
    for (int _f = 0; _f < (data.length - 1); _f++) {
      List f = data[_f];
      Map newRow = new Map();
      String searchStr = "";
      for (int h = 0; h < (head.length); h++) {
//        print("f: $_f  h:$h");
//        print(f);
        newRow[head[h]] = f[h] == Null ? " " : f[h];
        searchStr = "$searchStr ${f[h]}";
      }
      newRow['All'] = searchStr;
      if (mappedData.containsKey(f[(widget.hasCategoryColumn - 1)])) {
        List<Map> categoryList = mappedData[f[(widget.hasCategoryColumn - 1)]];
        categoryList.add(newRow);
        mappedData[f[(widget.hasCategoryColumn - 1)]] = categoryList;
      } else {
        mappedData[f[(widget.hasCategoryColumn - 1)]] = [newRow];
      }
    }
    return mappedData;
  }

  Widget goodsList() {
    if (data == null) return Text('یک گروه کالایی انتخاب کنید');
    return ListView.builder(
        shrinkWrap: true,
        physics: ScrollPhysics(),
        itemCount: _categoryColumnGroup.length,
        itemBuilder: (BuildContext context, int index) {
          List<String> _keys = _categoryColumnGroup.keys.toList();
          List<Map> _mp = _categoryColumnGroup[_keys[index]];
          List<Widget> _mpCards = [];

          for (int _m = 0; _m < (_mp.length); _m++) {
            String textToShow = "";
            for (int h = 0; h < head.length; h++) {
              textToShow = "$textToShow ";
              if (_mp[_m][head[h]] != null) {
                textToShow =
                    "$textToShow ${head[h]} :\n ${_mp[_m][head[h]]} \n";
              }
            }
            _mpCards.addAll([
              Divider(
                color: Colors.amber,
                endIndent: 100,
              ),
              ListTile(
                dense: true,
//                            decoration: BoxDecoration(
//                                border: Border(top: BorderSide(width: 2.0))),
//                            margin: EdgeInsets.all(10.0),
                title: Text(
                  textToShow,
                  textDirection: TextDirection.rtl,
                  textAlign: TextAlign.right,
                ),
              )
            ]);
          }
          String title = _keys[index];

          return ExpansionTile(
            title: Text(
              title,
              textDirection: TextDirection.rtl,
              textAlign: TextAlign.right,
              style: TextStyle(fontFamily: "Sahel"),
            ),
            children: _mpCards,
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    Future<List<List>> _tbl =
        csv(widget.website, widget.tableName, widget.titleFa);
    return Scaffold(
      body: ListView(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              onChanged: (value) {},
              controller: editingController,
              decoration: InputDecoration(
                  labelText: i18nLocale[ourLocale]["search"],
//                hintText: "Search",
                  prefixIcon: Icon(Icons.search),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(25.0)))),
            ),
          ),
          FutureBuilder(
              future: _tbl,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.data == null) {
                  return Card(
                    child: Text(i18nLocale[ourLocale]['reciving']),
                  );
                } else {
//                  setState(() {
                  head = snapshot.data[0];
                  data = snapshot.data[1];
                  _categoryColumnGroup = categoryColumnGroup(snapshot.data);
//                  });

                  List<DropdownMenuItem<String>> _dm = [];
                  List<String> mapKeys = _categoryColumnGroup.keys.toList();
                  for (var __k = 0; __k < mapKeys.length; __k++) {
                    String k = mapKeys[__k];
                    DropdownMenuItem<String> _k = new DropdownMenuItem<String>(
                      value: k,
                      child: Text(
                        k,
                      ),
                    );
                    try {
                      _dm.add(_k);
                    } catch (e) {
                      print(e);
                      print(_k);
                    }
                  }
                  if (firstTimeDropDownMenu)
                    selectedValueDropDownMenu = mapKeys[0];
                  return Directionality(
                      textDirection: TextDirection.rtl,
                      child: DropdownButton<String>(
//                        style: TextStyle(fontFamily: "Sahel"),
                        isExpanded: true,
                        isDense: true,
//                    iconSize: 28.5,
                        icon: Icon(Icons.arrow_drop_down_circle),
                        items: _dm,
                        value: selectedValueDropDownMenu,
                        onChanged: (String newV) {
                          setState(() {
                            firstTimeDropDownMenu = false;
                            selectedValueDropDownMenu = newV;
                          });
                        },
                      ));
                }
              }),
          goodsList(),
        ],
      ),
    );
  }
}
